<?php
namespace jy_peiorder;
defined('BY_JYA') or exit('error');
/*
  配送订单
	
*/
class order extends \plugin{
	/*
		系统指派，peisong_id是MID
	*/
	public function order_pai($order){
		$order_id=intval($order['id']);
		$allusers=array();
		if($order['merchid']){
			$areas=pdo_getall('jy_peiorder_area',array('uniacid'=>$_SESSION['uniacid'],'merchid OR'=>'merchid=0 or merchid = \''.$order['merchid'].'\''));
			foreach($areas as &$item){
				$users=pdo_getall('jy_peiorder_member',array('level_id'=>$item['id'],'status'=>1),'mid');
				foreach($users as $uv){
					$allusers[]=$uv;
				}
			}
		}else{
			$users=pdo_getall('jy_peiorder_member',array('status'=>1,'uniacid'=>$_SESSION['uniacid']),'mid');
			foreach($users as $uv){
				$allusers[]=$uv;
			}
		}
		$nums=count($allusers);
		$key=rand(0,$nums-1);
		$key=$key?:0;
		$peisong_id=$allusers[$key]['mid'];
		if(!$peisong_id){
			return false;
		}
		$params=array('order_id'=>$order_id,'peisong_id'=>$peisong_id);
		$this->order_sendget($params);
		return true;
	}
	/*
		抢单peisong_id是MID
	*/
	public function order_get($params){
		$order_id=intval($params['order_id']);
		$peisong_id=intval($params['peisong_id']);
		//兼容错误，传过来的是ID而不是MID的时候！
		$mid=pdo_getcolumn('jy_peiorder_member',array('mid'=>$peisong_id,'uniacid'=>$_SESSION['uniacid']),'mid');
		if(!$mid){
			$peisong_id=pdo_getcolumn('jy_peiorder_member',array('id'=>$peisong_id),'mid');
		}
		$isget=pdo_getcolumn('jy_weishop_order',array('id'=>$order_id),'status');
		if($isget==2){
			exi('该订单已被别人抢单了！','error');
		}
		pdo_update('jy_weishop_order',array('peisong_id'=>$peisong_id,'status'=>2,'send_status'=>1),array('id'=>$order_id));
		$is_dingpei=pdo_getcolumn('jy_weishop_order',array('id'=>$order_id),'is_dingpei');
		if(!$is_dingpei){
			$this->create_sendlog($order_id,$peisong_id,1);
		}else{
			$peiset=$this->pdo_get('peiset',array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
			if($peiset){
				$goods=$peiset['goods']?json_decode($peiset['goods'],true):array();
				foreach($goods as &$gv){
					if($gv['goodsnum'] || $gv['total']){
						$gv['lastnum']=$gv['goodsnum']?:$gv['total'];
					}
				}
			}
			$this->upsendlog($goods,$order_id);
		}
		$this->model('notice')->notice_orderget($order_id);
		model('jy_weishop/order')->order_send($order_id,$params,true);
		return true;
	}
	/*
		发送订单给配送员
	*/
	public function order_sendget($params){
		$order_id=intval($params['order_id']);
		$peisong_id=intval($params['peisong_id']);
		//兼容错误，传过来的是ID而不是MID的时候！
		$mid=pdo_getcolumn('jy_peiorder_member',array('mid'=>$peisong_id,'uniacid'=>$_SESSION['uniacid']),'mid');
		if(!$mid){
			$peisong_id=pdo_getcolumn('jy_peiorder_member',array('id'=>$peisong_id),'mid');
		}
		pdo_update('jy_weishop_order',array('peisong_id'=>$peisong_id,'status'=>2,'send_status'=>13),array('id'=>$order_id));
		$is_dingpei=pdo_getcolumn('jy_weishop_order',array('id'=>$order_id),'is_dingpei');
		if(!$is_dingpei){
			$this->create_sendlog($order_id,$peisong_id);
		}
		$this->model('notice')->notice_orderget($order_id);
		return true;
	}
	/*
		配送员确定接单
	*/
	public function order_checkget($order_id){
		pdo_update('jy_weishop_order',array('peisong_id'=>$_SESSION['uid'],'status'=>2,'send_status'=>1),array('id'=>$order_id));
		$this->up_sendlog($order_id,$_SESSION['uid'],2);
		$this->model('notice')->notice_orderget($order_id);
		model('jy_weishop/order')->order_send($order_id,'',true);
		return true;
	}
	/*
		转单超时
	*/
	public function order_checktime($order_id=0){
		$setting=$this->plugin_setting('setting');
		$send_status13_time=intval($setting['send_status13_time']);
		if(!$send_status13_time){
			return false;
		}
		if($order_id){
			$sendlog=pdo_get('jy_peiorder_sendlog',array('status'=>0,'mid'=>$_SESSION['uid'],'order_id'=>$order_id));
			if($sendlog['createtime']){
				$lasttime=$sendlog['createtime']+$send_status13_time*60;
				if($lasttime<TIMESTAMP){
					pdo_update('jy_weishop_order',array('peisong_id'=>0,'status'=>1,'send_status'=>12),array('id'=>$order_id));
					$this->up_sendlog($order_id,$sendlog['mid'],3);
				}
			}
		}else{
			$sendlogs=pdo_getall('jy_peiorder_sendlog',array('status'=>0,'uniacid'=>$_SESSION['uniacid']));
			foreach($sendlogs as $sendlog){
				$order_id=$sendlog['order_id'];
				if($sendlog['createtime']){
					$setting=$this->plugin_setting('setting');
					$lasttime=$sendlog['createtime']+$send_status13_time*60;
					if($lasttime<TIMESTAMP){
						pdo_update('jy_weishop_order',array('peisong_id'=>0,'status'=>1,'send_status'=>12),array('id'=>$order_id));
						$this->up_sendlog($order_id,$sendlog['mid'],3);
					}
				}
			}
		}
		return true;
	}
	/*
		完成订单
	*/
	public function order_receive($order_id){
		$order=pdo_get('jy_weishop_order',array('id'=>$order_id),array('ordersn','price','is_dingpei'));
		$goodsnum=0;
		if($order['is_dingpei']){
			$item['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id));
			foreach($item['goods'] as &$g){
				if($goodsnum<$g['goodsnum']){
					$goodsnum=$g['goodsnum'];
				}
			}
			$issendnum=pdo_count('jy_peiorder_sendlog',array('status'=>2,'order_id'=>$order_id));
		}
		if($goodsnum<=$issendnum+1 || !$order['is_dingpei']){
			pdo_update('jy_weishop_order',array('send_status'=>4),array('id'=>$order_id));
			model('jy_weishop/order')->order_receive($order_id);	
		}
		$this->model('order')->up_sendlog($order_id,'',2);
		return true;
	}
	/*
		接单日志
	*/
	public function create_sendlog($order_id,$mid=0,$status=0,$day='',$sendtype='',$daygoods=array()){
		$mid=$mid?:$_SESSION['uid'];
		$order=pdo_get('jy_weishop_order',array('id'=>$order_id),array('merchid','sendtype','mid','is_dingpei'));
		$peiset=$this->pdo_get('peiset',array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		$peisetgoods=json_decode($peiset['goods'],true);
		$num=0;
		foreach($peisetgoods as $k=>$g){
			$num +=$g['num'];
		}
		if($num<=0 && $order['is_dingpei'] && !$daygoods){
			exi('未配置任何商品和数量，不能发起配送！','error');
		}
		if($order['is_dingpei']){
			$goods=$daygoods?$daygoods['goods']:$peiset['goods'];
			if(!$daygoods['goods']){
				$this->pdo_delete('sendlog',array('day'=>$day,'uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
				return false;
			}
		}else{
			$goods=pdo_getall('jy_weishop_order_goods',array('orderid'=>$order_id),array('goodsid','price','total'));
			foreach($goods as &$g){
				$g['title']=pdo_getcolumn('jy_weishop_goods',array('id'=>$g['goodsid']),'title');
				$g['num']=$g['total'];
			}
		}
		$data=array(
				'mid'=>$mid,
				'merchid'=>$order['merchid'],
				'order_id'=>$order_id,
				'sendtype'=>$sendtype?:$order['sendtype'],
				'day'=>$day,
				'daytime'=>strtotime($day),
				'goods'=>ijson_encode($goods),
				'status'=>$status,
		);
		$islog=$this->pdo_get('sendlog',array('day'=>$day,'uniacid'=>$_SESSION['uniacid'],'order_id'=>$order_id));
		if($islog['id']){
			$this->update('sendlog',$data,array('id'=>$islog['id'],'uniacid'=>$_SESSION['uniacid']));
		}else{
			$data['uniacid']=$_SESSION['uniacid'];
			$data['order_id']=$order_id;
			$data['createtime']=TIMESTAMP;
			$data['buymid']=$order['mid'];
			$this->insert('sendlog',$data);
		}
		return true;
	}
	public function upsendlog($goods=array(),$order_id=0){
		$goodsnum=array();
		foreach($goods as $k=>$gv){
			$nums=$this->get_goodslognum($order_id,$gv);
			$goodsnum[$k]=$nums['lastnum'];
		}
		for($i=1;$i<=365;$i++){
			$daytime=time()+$i*24*3600;
			$week = date('w', $daytime);
			$day=date('Y-m-d',$daytime);
			$daygoods=array('key'=>1);
			$isadd=0;
			foreach($goods as $k=>$gv){
				if($goodsnum[$k]<=0){
					continue;
				}
				$isadd=1;
				if($gv['numset'][$week]['num']>0){
					$goodsnum[$k]-=$gv['numset'][$week]['num'];
					$key=$gv['optionid']?$gv['goodsid'].'_'.$gv['goodsid']:$gv['goodsid'];
					$daygoods['goods'][$key]=array(
						'num'=>$gv['numset'][$week]['num'],
						'title'=>$gv['goods_title']?:$gv['title'],
						'goodsid'=>$gv['goodsid'],
						'optionid'=>$gv['optionid'],
						'selespename'=>$gv['selespename'],
					);
				}
			}
			if(!$isadd){
				break;
			}
			$this->create_sendlog($order_id,0,0,$day,'',$daygoods);
		}
		return true;
	}
	/*
		uplog
	*/
	public function up_sendlog($order_id,$mid=0,$status=0){
		$mid=$mid?:$_SESSION['uid'];
		$this->pdo_update('sendlog',array('status'=>$status),array('mid'=>$mid,'order_id'=>$order_id,'status'=>array(0,1),'uniacid'=>$_SESSION['uniacid']));
		//完成日志
		if($status==2){
			$order=pdo_get('jy_weishop_order',array('id'=>$order_id),array('merchid','sendtype','mid','is_dingpei'));
			$list=pdo_getall('jy_peiorder_sendlog',array('mid'=>$mid,'order_id'=>$order_id,'status'=>array(0,1),'uniacid'=>$_SESSION['uniacid']));
			foreach($list as $item){
				$this->create_orderlog($item['id'],'',$order['is_dingpei']);
			}
		}
		return true;
	}
	//获取可编辑的商品数量
	public function get_goodslognum($order_id=0,$goods=array()){
		$mday=date("Y-m-d",strtotime("+1 day"));
		$mdaytime=strtotime($mday);
		$params=array('optionid'=>intval($goods['optionid']),'goodsid'=>$goods['goodsid']?:$goods['id'],'orderid'=>$order_id,'uniacid'=>$_SESSION['uniacid']);
		$order_goods=pdo_get('jy_weishop_order_goods',$params,array('istaocan','goodsid','optionid','orderid','price','total','goodsnum'));
		$order_goods['goodsnum']=$order_goods['goodsnum']?:$order_goods['total'];
		$goodsid=$order_goods['goodsid'];
		$optionid=$order_goods['optionid'];
		$params=array('status'=>array(1,2),'uniacid'=>$_SESSION['uniacid']);
		$list=pdo_getall('jy_peiorder_sendlog',$params);
		$isnum=0;
		foreach($list as $item){
			$peisetgoods=json_decode($item['goods'],true);
			foreach($peisetgoods as $k=>$g){
				if($goodsid && $g['goodsid']==$goodsid && intval($g['optionid'])==$optionid){
					$isnum +=$g['num'];
				}
			}
		}
		$params=array('daytime <='=>$mdaytime,'status'=>0,'uniacid'=>$_SESSION['uniacid']);
		$list=pdo_getall('jy_peiorder_sendlog',$params);
		foreach($list as $item){
			$peisetgoods=json_decode($item['goods'],true);
			foreach($peisetgoods as $k=>$g){
				if($goodsid && $g['goodsid']==$goodsid && intval($g['optionid'])==$optionid){
					$isnum +=$g['num'];
				}
			}
		}
		$res=array(
			'isnum'=>$isnum,
			'lastnum'=>$order_goods['goodsnum']-$isnum,
			'goodsnum'=>$order_goods['goodsnum'],
		);
		return $res;
	}
	public function get_goodsnum($order_id=0,$goodsid=0){
		$params=array('status'=>2,'uniacid'=>$_SESSION['uniacid']);
		if($order_id){
			$params['order_id']=$order_id;
		}
		$list=pdo_getall('jy_peiorder_sendlog',$params);
		$isnum=0;
		foreach($list as $item){
			$peisetgoods=json_decode($item['goods'],true);
			foreach($peisetgoods as $k=>$g){
				if($goodsid && $g['goodsid']==$goodsid){
					$isnum +=$g['num'];
				}else{
					$isnum +=$g['num'];
				}
			}
		}
		return $isnum;
	}
	public function get_goodslastnum($order_id=0,$goodsid=0){
		$mid=$mid?:$_SESSION['uid'];
		$params=array('mid'=>$_SESSION['uid'],'merchid'=>$_SESSION['onemerchid']);
		if($goodsid){
			$params['goodsid']=$goodsid;
		}
		if($goodsid){
			$params['orderid']=$order_id;
		}
		$goodsnum=pdo_getsum('jy_weishop_order_goods',$params,'goodsnum');
		$isnum=$this->get_goodsnum(0,0,true);
		$lastnum=$goodsnum-$isnum;
		return $lastnum;
	}
	public function dingpei1($order_id,$day='',$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$nowlog=pdo_get('jy_peiorder_sendlog',array('mid'=>$mid,'order_id'=>$order_id,'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		if(!$nowlog['id']){
			$this->create_sendlog($order_id,$mid,1,$day,1);
		}else{
			$this->pdo_update('sendlog',array('status'=>1,'day'=>$day),array('mid'=>$mid,'order_id'=>$order_id,'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		}
		return true;
	}
	public function dingpei2($order_id,$status=0,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$this->pdo_update('sendlog',array('status'=>2),array('mid'=>$mid,'order_id'=>$order_id,'status'=>1,'uniacid'=>$_SESSION['uniacid']));
		$list=pdo_getall('jy_peiorder_sendlog',array('mid'=>$mid,'order_id'=>$order_id,'status'=>1,'uniacid'=>$_SESSION['uniacid']));
		foreach($list as $item){
			$this->create_orderlog($item['id'],0,1);
		}
		return true;
	}
	public function sendlog1($logid,$day='',$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$nowlog=pdo_get('jy_peiorder_sendlog',array('id'=>$logid,'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		if(!$nowlog['id']){
			exi('该配送订单不存在！','error');
		}else{
			$this->pdo_update('sendlog',array('status'=>1),array('id'=>$logid,'status'=>0,'uniacid'=>$_SESSION['uniacid']));
		}
		return true;
	}
	public function sendlog2($logid,$status=0,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$nowlog=pdo_get('jy_peiorder_sendlog',array('id'=>$logid,'status'=>1,'uniacid'=>$_SESSION['uniacid']));
		if(!$nowlog['id']){
			exi('该配送订单不存在！','error');
		}else{
			$this->pdo_update('sendlog',array('status'=>2),array('id'=>$logid,'status'=>1,'uniacid'=>$_SESSION['uniacid']));
		}
		$this->create_orderlog($logid,0,1);
		return true;
	}
	/*
		创建结算订单
	*/
	function create_orderlog($logid,$mid=0,$is_dingpei=0,$get_money=0){
		$mid=$mid?:$_SESSION['uid'];
		//按商品/按件
		$sendlog=pdo_get('jy_peiorder_sendlog',array('id'=>$logid,'uniacid'=>$_SESSION['uniacid']));
		$order=pdo_get('jy_weishop_order',array('id'=>$sendlog['order_id']),array('ordersn','price','merchid','is_dingpei'));
		$peisetgoods=json_decode($sendlog['goods'],true);
		$get_money=$this->model('model')->get_peifee($order,$mid,$peisetgoods);
		$data=array(
				'uniacid'=>$_SESSION['uniacid'],
				'mid'=>$mid,
				'merchid'=>$order['merchid'],
				'ordersn'=>$order['ordersn'],
				'logid'=>$logid,
				'ordersn'=>$order['ordersn'],
				'get_price'=>$get_money,
				'get_money'=>$get_money,
				'is_dingpei'=>$is_dingpei?:$order['is_dingpei'],
				'createtime'=>TIMESTAMP,
				'status'=>0,
		);
		$this->insert('orderlog',$data);
		return true;
	}
	/*
		报单
	*/
	function baodan_check($baodanid){
		//整理订单数据
		$post=pdo_get('jy_peiorder_baodan',array('id'=>$baodanid));
		$post['address']=json_decode($post['address'],true);
		$post['goods']=json_decode($post['goods'],true);
		$post['list']=$post['goods'];
		$post['total_price']=$post['goodsprice'];
		foreach($post['list'] as &$lv){
			$lv['goodsid']=$lv['id'];
			$api_data=pdo_getcolumn('jy_weishop_goods',array('id'=>$lv['goodsid']),'api_data');
			$api_data=json_decode($api_data,true);
			if($api_data['dingpei']){
				$post['is_dingpei']=1;
			}
			if($lv['optionid']){
				$lv['options']=pdo_get('jy_weishop_goods_option',array('goodsid'=>$lv['goodsid'],'id'=>$lv['optionid']));
			}
		}
		/*$data=array(
			'mobile'=>trim($post['mobile']),
			'name'=>trim($post['realname']),
			'pcd'=>ijson_encode($post['address']['pcd']),
			'address'=>trim($post['address']['address'])
		);
		$data['mid']=$post['mid'];
		$data['uniacid']=$_SESSION['uniacid'];
		pdo_insert('core_address',$data);
		$post['addressid'] = pdo_insertid();*/
		$_SESSION['order']=$post;
		$new_order=model('jy_weishop/get_order')->new_order($post);
		$new_order['mid']=$post['mid'];
		$new_order['plugin_name']='jy_peiorder';
		$new_order['status']=1;
		$new_order['is_dingpei']=$post['is_dingpei'];
		$order_id=model('jy_weishop/order')->create($new_order);
		pdo_update('jy_weishop_order',array('status'=>1,'ispay'=>1,'paytype'=>'apipay'),array('id'=>$order_id));
		if($post['peiset']){
			$peiset=json_decode($post['peiset'],true);
			//更新配送设置
			$data=array(
				'set_mid'=>$_SESSION['uid'],
				'days'=>trim($peiset['days']),
				'times'=>trim($peiset['times']),
				'goods'=>ijson_encode($peiset['goods']),
			);
			$data['uniacid']=$_SESSION['uniacid'];
			$data['mid']=$post['mid'];
			$data['merchid']=$_SESSION['onemerchid'];
			$data['order_id']=$order_id;
			$data['createtime']=time();
			$this->insert('peiset',$data);
		}
		if($post['peisong_id']){
			$params=array('order_id'=>$order_id,'peisong_id'=>$post['peisong_id']);
			$this->order_get($params);
		}
		$this->order=model('jy_weishop/order')->get_order($order_id);
		$event=array(
			'type'=>'pay',
			'order'=>$this->order,
		);
		if($this->order['merchid'] && $this->plugin_exists('jy_merch')){
			model('jy_merch/model')->up_pay($this->order);
		}
		plugin('jy_weishop')->publish('order.change',$event);
		return true;
	}
	/*
		订单升级为待结算
	*/
	public function cash_orderlog(){
		$cashdays=$this->setting['cash_day']?:1;
		$cashtime = mktime(0,0,0,date('m'),date('d')-$cashdays,date('Y'));
		$orderlog=pdo_getall('jy_peiorder_orderlog',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid'],'status'=>0,'createtime <'=>$cashtime));
		foreach($orderlog as $item){
			pdo_update('jy_peiorder_orderlog',array('status'=>1),array('id'=>$item['id'],'uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']));
		}
		return true;
	}
	/*
		待结算订单升级为结算完成/未结算
	*/
	public function change_orderlog($mid,$status=0){
		$orderlog=pdo_getall('jy_peiorder_orderlog',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$mid,'status'=>1));
		foreach($orderlog as $item){
			pdo_update('jy_peiorder_orderlog',array('status'=>1),array('id'=>$item['id'],'uniacid'=>$_SESSION['uniacid'],'status'=>$status));
		}
		return true;
	}
	/*
		审核结算单
	*/
	public function check_balance($balance_id,$status,$remark=''){
		$update=array(
			'status'=>$status,
			'remark'=>$remark,
		);
		$this->update('cashlog',$update,array('id'=>$balance_id));
	}
	/*
		打款结算单
	*/
	public function pay_balance($balance_id,$pay_type='',$wxgid='',$pay_trade_no=''){
		$balance=$this->get('cashlog',array('id'=>$balance_id,'uniacid'=>$_SESSION['uniacid']));
		if(!$balance || $balance['status']!=1){
			exi('结算单不存在或者不符合打款条件，打款失败！','error');
		}
		$pay_types=array_keys($this->pay_types);
		if(!$pay_type || !in_array($pay_type,$pay_types)){
			//exi('未设置打款方式或者打款方式不合法，打款失败！','error');
		}
		$pay_type=$this->pay_types2[$pay_type];
		$func_name='pay_balance_by_'.$pay_type;
		$trade_no=$this->$func_name($balance['mid'],$balance['final_money'],$balance['balancesn'],$wxgid);
		$update=array(
			'status'=>3,
			'applysn'=>$trade_no=='pay_trade_no'?$pay_trade_no:$trade_no,
		);
		if($pay_type){
			$update['paytype']=$pay_type;
		}
		$this->update('cashlog',$update,array('id'=>$balance['id']));
		return true;
	}
	/*
		打款到余额
	*/
	protected function pay_balance_by_credit($mid,$money,$balancesn){
		return cfc('core')->member_credit($mid,'credit2',$money,true,$this->plugin_name,$remark='分销佣金打款');
	}
	/*
		打款到微信零钱
	*/
	protected function pay_balance_by_wechat($mid,$money,$balancesn,$wxgid=''){
		if($wxgid){
			$wxapp=pdo_get('core_account_wxapp',array('id'=>$wxgid,'uniacid'=>$_SESSION['uniacid']),array('appid','mchid','paykey'));
		}
		$params=array(
			'appid'=>$wxapp['appid']?:'',
			'mch_id'=>$wxapp['mchid']?:'',
			'openid'=>$mid,
			'mch_billno'=>$balancesn,
			'money'=>$money,
			'wxgid'=>$wxgid,
			'remark'=>'代理商佣金发放',
		);
		$res=cfc('wechat_pay')->mch_pay($params);
		return $res['payment_no'];
	}
	/*
		打款到支付宝
	*/
	protected function pay_balance_by_alipay($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到支付宝！','error');
	}
	/*
		打款到银行账户
	*/
	protected function pay_balance_by_union($mid,$money,$balancesn){
		return 'pay_trade_no';
		exi('暂不支持打款到银行账户！','error');
	}
}